package y2018.date1024.shufaxinshang;

import com.lu.jdog.util.TextUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PageUtil {

    private Document document;
    private String baseUrl;

    private PageUtil(String baseUrl) {
        this.baseUrl = baseUrl;
        try {
            this.document = Jsoup.connect(baseUrl).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static PageUtil newInstance(String baseUrl) {
        return new PageUtil(baseUrl);
    }

    public String getTitle() {
        String title = document.select("h1").text();
        if (TextUtil.isEmpty(title)) {
            String titleStr = document.select("title").text();
            int _index = titleStr.indexOf("_");
            if (_index == -1) {
                title = titleStr;
            } else {
                title = titleStr.substring(0, _index);
            }
        }
        return title;
    }

    public List<String> getUrlList() {
        List<String> urlList = new ArrayList<>();
        urlList.add(baseUrl);

        Elements els = document.select(".pageNavBox.list div");
        int size = els.size();
        if (size == 0) {
            return urlList;
        }
        Element elCount = els.get(size - 2);
        String lastPage = elCount.text();
//			if (lastPage.contains("...")) {
//				lastPage = lastPage.replaceAll("\\.| ", "");
//			}
        Pattern pattern = Pattern.compile("[\\d]+");
        Matcher matcher = pattern.matcher(lastPage);
        matcher.find();
        lastPage = matcher.group();
        int count = Integer.parseInt(lastPage);

        int dotIndex = baseUrl.lastIndexOf(".");
        String baseStr = baseUrl.substring(0, dotIndex);
        String suffixStr = baseUrl.substring(dotIndex);

        for (int i = 2; i <= count; i++) {
            String url = baseStr + "_" + i + suffixStr;
            urlList.add(url);
        }
        return urlList;
    }
}
